package com.sdap2.dao;

import com.sdap2.common.dao.LogicDAO;
import com.sdap2.entity.Device;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.Query;
import java.util.List;

@Repository
public interface DeviceDAO extends LogicDAO<Device, Long> {
    boolean existsBySerialNumber(String serialNumber);
    
    @Query("SELECT d FROM Device d WHERE d.serialNumber = :serialNumber AND d.isDeleted = false")
    Optional<Device> findBySerialNumber(String serialNumber);
    
    @Query("SELECT d FROM Device d WHERE UPPER(d.serialNumber) LIKE UPPER(:serialNumber)")
    Optional<Device> findBySerialNumberIgnoreCase(String serialNumber);
    
    Page<Device> findAllByGreenhouseId(Long greenhouseId, Pageable pageable);
    
    boolean existsBySerialNumberAndIdNot(String serialNumber, Long id);
    
    @Query("SELECT d FROM Device d WHERE d.serialNumber LIKE %:serialNumber% AND d.isDeleted = false")
    List<Device> findBySerialNumberContaining(String serialNumber);
    
    @Query("SELECT d FROM Device d WHERE d.serialNumber = :serialNumber")
    Optional<Device> findByExactSerialNumber(String serialNumber);
    
    @Query("SELECT d FROM Device d WHERE REPLACE(d.serialNumber, ' ', '') = REPLACE(:serialNumber, ' ', '')")
    Optional<Device> findBySerialNumberNoSpaces(String serialNumber);
    
    List<Device> findAllByGreenhouseId(Long greenhouseId);
    
    void deleteAllByGreenhouseId(Long greenhouseId);
    
    @Query("SELECT d FROM Device d LEFT JOIN FETCH d.greenhouse g LEFT JOIN FETCH g.user WHERE d.serialNumber = :serialNumber")
    Optional<Device> findBySerialNumberWithGreenhouse(String serialNumber);
    
    @Query("SELECT d FROM Device d LEFT JOIN FETCH d.greenhouse WHERE d.greenhouse.id = :greenhouseId")
    Page<Device> findAllByGreenhouseIdWithFetch(@Param("greenhouseId") Long greenhouseId, Pageable pageable);
} 